package com.mantru.iotpot.setting.Adapter;

import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.mantru.iotpot.R;

import java.util.List;

public class OtherWiFiAdapter extends RecyclerView.Adapter<OtherWiFiAdapter.ViewHolder> {
    private final List<String> wifiList;
    private final Context context;
    public AlertDialog waitDialog;
    private OnWiFiConnectListener listener;

    public OtherWiFiAdapter(Context context, List<String> wifiList, OnWiFiConnectListener listener) {
        this.context = context;
        this.wifiList = wifiList;
        this.listener = listener;
    }

    @NonNull
    @Override
    public OtherWiFiAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_other_wifi, parent, false);
        return new OtherWiFiAdapter.ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull OtherWiFiAdapter.ViewHolder holder, int position) {
        String wifiInfo = wifiList.get(position);
        holder.name.setText(wifiInfo);
        holder.box.setOnClickListener(v -> {
            showCustomDialog(v.getContext(), wifiInfo);
        });
    }

    @Override
    public int getItemCount() {
        return wifiList.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        private final TextView name;
        private final RelativeLayout box;
        public ViewHolder(View view) {
            super(view);
            name = view.findViewById(R.id.adapter_other_wifi_name);
            box = view.findViewById(R.id.adapter_other_wifi_box);
        }
    }

    private void showCustomDialog(Context context, String wifiInfo) {
        View dialogView = LayoutInflater.from(context).inflate(R.layout.adapter_conecter_wifi_dialog, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setView(dialogView);
        TextView wifi_name = dialogView.findViewById(R.id.conecter_wifi_dialog_name);
        EditText editText = dialogView.findViewById(R.id.conecter_wifi_dialog_edtext);
        Button cancel = dialogView.findViewById(R.id.conecter_wifi_dialog_cancel);
        Button confirm = dialogView.findViewById(R.id.conecter_wifi_dialog_confirm);
        ImageView img = dialogView.findViewById(R.id.conecter_wifi_dialog_cencle_img);
        wifi_name.setText(wifiInfo);
        AlertDialog dialog = builder.create();
        cancel.setOnClickListener(v -> dialog.dismiss());
        confirm.setOnClickListener(v -> {
            String password = editText.getText().toString();
            connectToWifi(context, wifiInfo, password);
            dialog.dismiss();
        });
        img.setOnClickListener(v -> dialog.dismiss());
        dialog.show();

        if (dialog.getWindow() != null) {
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        }
        dialog.setCanceledOnTouchOutside(false);
    }

    private void connectToWifi(Context context, String ssid, String password) {
        waitDialog = new AlertDialog.Builder(context)
                .setView(LayoutInflater.from(context).inflate(R.layout.adapter_wait_conecter_wifi_dialog, null))
                .create();
        waitDialog.show();
        if (waitDialog.getWindow() != null) {
            waitDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        }
        // 设置弹窗不能通过触摸外部关闭
        waitDialog.setCanceledOnTouchOutside(false);

        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (wifiManager == null) {
            Toast.makeText(context, "无法获取 WiFi 服务", Toast.LENGTH_SHORT).show();
            if (waitDialog != null && waitDialog.isShowing()) {
                waitDialog.dismiss();
            }
            return;
        }
        if (ActivityCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(context, "权限不足", Toast.LENGTH_SHORT).show();
            if (waitDialog != null && waitDialog.isShowing()) {
                waitDialog.dismiss();
            }
            return;
        }
        removeExistingNetwork(wifiManager, ssid);
        WifiConfiguration config = new WifiConfiguration();
        config.SSID = "\"" + ssid + "\"";
        if (isWiFiEncrypted(wifiManager, ssid)) {
            config.preSharedKey = "\"" + password + "\"";
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        } else {
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        }
        int networkId = wifiManager.addNetwork(config);
        if (networkId != -1) {
            boolean isEnabled = wifiManager.enableNetwork(networkId, true);
            if (isEnabled) {
                Toast.makeText(context, "正在连接到 WiFi: " + ssid, Toast.LENGTH_SHORT).show();
                wifiManager.reconnect();
            } else {
                Toast.makeText(context, "启用网络失败", Toast.LENGTH_SHORT).show();
                if (waitDialog != null && waitDialog.isShowing()) {
                    waitDialog.dismiss();
                }
            }
        } else {
            Toast.makeText(context, "添加网络失败，请检查配置", Toast.LENGTH_SHORT).show();
            if (waitDialog != null && waitDialog.isShowing()) {
                waitDialog.dismiss();
            }
        }

        if (listener != null) {
            listener.onWiFiConnectStateChanged();
        }
    }

    private boolean isWiFiEncrypted(WifiManager wifiManager, String ssid) {
        if (ActivityCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return true;
        }
        List<ScanResult> scanResults = wifiManager.getScanResults();
        for (ScanResult result : scanResults) {
            if (result.SSID.equals(ssid)) {
                return result.capabilities.contains("WEP") || result.capabilities.contains("WPA") || result.capabilities.contains("EAP");
            }
        }
        return true;
    }

    private void removeExistingNetwork(WifiManager wifiManager, String ssid) {
        if (ActivityCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks();
        if (configs != null) {
            for (WifiConfiguration config : configs) {
                if (config.SSID != null && config.SSID.equals("\"" + ssid + "\"")) {
                    wifiManager.removeNetwork(config.networkId);
                    wifiManager.saveConfiguration();
                }
            }
        }
    }

    public interface OnWiFiConnectListener {
        void onWiFiConnectStateChanged();
    }
}